import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { ReactComponent as RVSIcon } from '@app-base/assets/svg-icons/commands/product/bracket/reverse-button.svg';
import { wsApi } from '@app-base/server';
import { Button, Table, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import SupportFilter from './support-filter';

const ExaminesTableAntd: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<
    SupportFilterFields.BracketInfoMeta[]
  >([]);
  const [selectedRowKey, setSelectedRowKey] = useState<number | null>(null);
  const [selectedRow, setSelectedRow] =
    useState<SupportFilterFields.BracketInfoMeta | null>(null);

  const showModal = (record: SupportFilterFields.BracketInfoMeta) => {
    setSelectedRow(record);
    setIsModalOpen(true);
  };

  const handleCancel = () => setIsModalOpen(false);

  const columns: ColumnsType<SupportFilterFields.BracketInfoMeta> = [
    { title: '卡箍名称', dataIndex: 'clamp', align: 'center', width: 150 },
    { title: '支架名称', dataIndex: 'bracket', align: 'center', width: 180 },
    {
      title: '替换',
      dataIndex: 'replace',
      align: 'center',
      width: 80,
      render: (_, record) => (
        <Button
          onClick={() => showModal(record)}
          size='small'
        >
          更多选择
        </Button>
      ),
    },
    {
      title: '装配方向',
      dataIndex: 'result',
      align: 'center',
      width: 80,
      render: (_, record) => (
        <Tooltip title='反向'>
          <Button
            icon={<RVSIcon />}
            size='small'
            onClick={() => {
              wsApi.execAiCmd({
                c: 'ReverseBracket',
                o: record.row,
                name: record.clamp,
              });
            }}
          />
        </Tooltip>
      ),
    },
    {
      title: '确认结果',
      dataIndex: 'consequence',
      align: 'center',
      width: 60,
      render: (confirmed: boolean | null) => {
        if (confirmed === true)
          return (
            <CheckCircleOutlined style={{ color: 'green', fontSize: 18 }} />
          );
        if (confirmed === false)
          return <CloseCircleOutlined style={{ color: 'red', fontSize: 18 }} />;
        return (
          <CloseCircleOutlined
            style={{ color: 'gray', fontSize: 18, opacity: 0.4 }}
          />
        );
      },
    },
  ];

  useEffect(() => {
    SendExaminesCommand();
  }, []);

  const SendExaminesCommand = async () => {
    setLoading(true);
    try {
      const res = await wsApi.execAiCmd({ c: 'VerifyBrackets' });
      if (Array.isArray(res?.content)) {
        setDataSource(res.content); // 不做字段转换
      }
      setLoading(false);
    } catch (error) {
      console.error('请求 VerifyBrackets 接口失败:', error);
      setLoading(true);
    }
  };

  const handleRowClick = (record: SupportFilterFields.BracketInfoMeta) => {
    setSelectedRowKey(record.row);
    wsApi.execAiCmd({
      c: 'ChooseBracket',
      o: record.row,
      name: record.clamp,
    });
  };

  return (
    <>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={false}
        scroll={{ y: 420 }}
        loading={loading}
        size='small'
        bordered
        rowKey='row'
        rowClassName={(record) =>
          record.row === selectedRowKey ? 'bg-blue-100' : ''
        }
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
        })}
      />

      <SupportFilter
        open={isModalOpen}
        handleCancel={handleCancel}
        selectedRow={selectedRow}
        SendExaminesCommand={SendExaminesCommand}
      />
    </>
  );
};

export default React.memo(ExaminesTableAntd);
